package com.xwj.back.websocket;

import com.alibaba.fastjson2.JSONObject;
import com.xwj.back.mapper.UserMapper;
import com.xwj.back.pojo.User;
import com.xwj.back.utils.JwtAuthenticationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{token}")
public class WebSocketServer {
    //维护建立连接后每个客户端的WebSocketServer对象
    public static final ConcurrentHashMap<Integer,WebSocketServer> users =new ConcurrentHashMap<>();

    //在线人数
    private static final CopyOnWriteArraySet<User> onlineUser = new CopyOnWriteArraySet<>();

    private Session session = null;

    private User user;

    private static UserMapper userMapper;

    @Autowired
    public  void setUserMapper(UserMapper userMapper) {
        WebSocketServer.userMapper = userMapper;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 建立连接
        this.session = session;
       //  解析token,获取用户id
        Integer userId = JwtAuthenticationUtil.getUserId(token);
        this.user = userMapper.selectById(userId);
        JSONObject resp = new JSONObject();
        if(this.user != null) {
            users.put(userId, this);
            onlineUser.add(user);
            resp.put("onlineUser",onlineUser);
            resp.put("online",this.user);
            sendAllMessage(resp.toJSONString());//向所有客户端发送在线人数和上线的用户
        }else{
            this.session.close();
        }
    }

    @OnClose
    public void onClose() {
        // 关闭链接
        if(this.user != null){
            users.remove(this.user.getId());
            onlineUser.remove(this.user);
            JSONObject resp = new JSONObject();
            resp.put("onlineUser",onlineUser);
            resp.put("user",this.user);
            sendAllMessage(resp.toJSONString());
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 从Client接收消息
        JSONObject data = JSONObject.parse(message);
        Integer from = data.getInteger("from");//发送用户
        String text = data.getString("text");//发送内容
        Integer to = Integer.valueOf(data.getString("to"));//接收用户
        JSONObject resp = new JSONObject();
        resp.put("text",text);
        resp.put("from",from);
        sendMessageById(resp.toJSONString(),to);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

//    给指定用户发消息
    private void sendMessageById(String message,Integer userId){
        try {
            users.get(userId).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMessage(String message){
        //服务端向客户端发送消息
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //服务端发消息给所有用户
    public void sendAllMessage(String message){
//        发给所有在线的用户
        users.forEach((userId,webSocketServer) -> {
            try {
                webSocketServer.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
